'use strict'

import { app, protocol, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const path = require('path');

const { Menu } = require('electron');
Menu.setApplicationMenu(null); // 隐藏菜单栏



const isDevelopment = process.env.NODE_ENV !== 'production'

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

async function createWindow() {
  const win = new BrowserWindow({
    width: 1500,
    height: 800,
    webPreferences: {
      webSecurity: false,
      preload: path.join(__dirname, '../preload.js'), // 指定预加载脚本
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
    // win.webContents.openDevTools()
  }
}

// // 监听来自渲染进程的读取JSON文件请求
// ipcMain.handle('getJSON', async (event, filePath) => {
//   console.log('getJSON')
//   filePath = path.join(__dirname, filePath)
//   try {
//     const fileContent = fs.readFileSync(filePath, 'utf8');
//     const jsonObject = JSON.parse(fileContent);
//     return { success: true, data: jsonObject };
//   } catch (error) {
//     return { success: false, msg: error.message };
//   }
// });

// // 监听来自渲染进程的写入JSON文件请求
// ipcMain.handle('setJSON', async (event, filePath, jsonObject) => {
//   console.log('setJSON', filePath)
//   filePath = path.join(__dirname, filePath)
//   try {
//     const jsonString = JSON.stringify(jsonObject, null, 2); // 格式化JSON字符串，缩进2个空格
//     fs.writeFileSync(filePath, jsonString, 'utf8');
//     return { success: true };
//   } catch (error) {
//     return { success: false, msg: error.message };
//   }
// });

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }

  createWindow()
})


if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
